import React, { Component } from 'react';

import {
  Form,
  Input,
  Select,
  Checkbox,
  Button,
  AutoComplete,
  message,
  Upload,
} from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

import { layout, tailLayout } from '../../const.js';
import { addadmin, } from '../../apis/admin.js';

const { Option } = Select;
//输入框自动完成功能
const AutoCompleteOption = AutoComplete.Option;
export default class AddAdmin extends Component {
  state = {
    // button点击后弹框
    loading: false,
    imageUrl:``,
    fileList: [],//存放上传信息：比如路径、文件名
    imgList: [],//存放回显信息：修改时的路径、文件名
  }
  //表单事件
  onFinish = async (values) => {
    console.log("values", values);
    try {
      this.setState({ loading: true })
      const data = await addadmin(values);
      console.log("返回新增的数据", data);
      this.setState({ loading: false })
      //添加后表单清空
      //1.获取组件实例
      this.myform.resetFields();//重置表单
      //提示
      message.success("账号添加成功")
      //跳转
      this.props.history.push('/home/adminlist');
    } catch (error) {

      this.setState({ loading: false })
    }
  };

  onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
 
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }
  };
  render() {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <div>
        <Form
          className=" "
          {...layout}
          name="basic"
          initialValues={{
            remember: true,
          }}
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          ref={instance => this.myform = instance}
        >
          <Form.Item
            label={<div style={{ width: 100 }}>用户名</div>}
            name="adminname"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input placeholder='请输入用户名' />
          </Form.Item>

          <Form.Item

            label={<div style={{ width: 100 }}>密码</div>}
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input.Password autoComplete="newPassword" />
          </Form.Item>

          <Form.Item
            label={<div style={{ width: 100 }}>角色</div>}
            name="userGroup"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Select style={{ width: 120 }}  >
              <Option value="超级管理员">超级管理员</Option>
              <Option value="普通管理员">普通管理员</Option>
              <Option value="普通用户">普通用户</Option>
            </Select>
          </Form.Item>

          {/* <Form.Item
            label={<div style={{ width: 100 }}>头像</div>}
            name="imgname"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:3000/images/upload"
              beforeUpload={beforeUpload}
              onChange={this.handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </Form.Item> */}

          <Form.Item  {...tailLayout} name="remember" valuePropName="checked">
            <Checkbox>i agree</Checkbox>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit" loading={loading}>
              添加
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
}
function getBase64(img, callback) {
  console.log("img111111111", img, "callback", callback);
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img.file);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}


